#include <iostream>
#include <cstdlib>
#ifdef __APPLE__
#include <GLUT/glut.h> //CHANGE TO GL/ for Linux/Windows
//g++ glut.c -framework OpenGL -framework GLUT <--- build for mac
#else
include <GL/glut.h>
#endif
#include <OpenGl/Gl.h>

#include "texture_png.h"

using namespace std;




// function prototypes
void disp(void);
void keyb(unsigned char key, int x, int y);


// window identifier
static int win;

static textureInfo textures[32];

/**
 * The last GLUT-handle that is called
 *
 * @param void
 *
 * @return void
 */
void GLUThandle_idle(void)
{
	sleep(100);
	glutPostRedisplay();
}


int main(int argc, char **argv){
 
  //////////
  // INIT //
  //////////

    glutInitWindowSize(640,480);
    glutInitWindowPosition(40,40);
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH | GLUT_MULTISAMPLE);


	
	
	
	
	win = glutCreateWindow("Yet another teapot");

	//////////////
	// CALLBACK //
	//////////////
	
	glutDisplayFunc(disp);
	glutKeyboardFunc(keyb);
	glutIdleFunc(GLUThandle_idle);
	//    glutSetOption ( GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_CONTINUE_EXECUTION ) ;
	
  
  ////////////
  // OPENGL //
  ////////////

  // define the color we use to clearscreen 
  //glClearColor(0.0,0.0,0.0,0.0);

	/* OpenGL-configuration */
	glEnable(GL_TEXTURE_2D);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	glShadeModel(GL_FLAT);
	glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
	
	textures[0] = LoadTexturePNG("pic.png", GL_RGBA, 1);
	
	
	// enter the main loop
  glutMainLoop();

  return 0;
}




/**
 * Creates a rectangle with a texture
 *
 * @param fX X-coordinate (to the left)
 * @param fY Y-coordinate (to the top)
 * @param fZ Z-coordinate (z-index)
 * @param fW Width
 * @param fH Height
 * @param gluTexture The texture that is to be mapped to the rectangle
 *
 * @return void
 */
void createRectTextured(float fX, float fY, float fZ, float fW, float fH, GLuint gluTexture)
{
	/* Adjust coordinate to standard 2D-drawing.
	 * (0,0) == top left
	 * (0,maxY) == bottom left */
	//fY = uiHeight - fH - fY;
	
	glBindTexture(GL_TEXTURE_2D, gluTexture);
	
	glBegin(GL_QUADS);
	glTexCoord2f(1.0f, 1.0f); 		glVertex3f(fW + fX, fH + fY, fZ);
	glTexCoord2f(0.0f, 1.0f); 		glVertex3f(fX, fH + fY, fZ);
	glTexCoord2f(0.0f, 0.0f); 		glVertex3f(fX, fY, fZ);
	glTexCoord2f(1.0f, 0.0f); 		glVertex3f(fW + fX, fY, fZ);
	glEnd();
}


void disp(void){
	
	// do  a clearscreen
  glClear(GL_COLOR_BUFFER_BIT);
  
  // draw something
	createRectTextured(-0.5f, -0.5f, 0.0f, 1.0f, 1.0f, textures[0].gluiTexture);
	
	sleep(1);

  //glutPostRedisplay();
	glutSwapBuffers();
}

void keyb(unsigned char key, int x, int y){
  cout << "Pressed key " << key << " on coordinates (" << x << "," << y << ")";
  cout << endl;
  if(key == 'q'){
    cout << "Got q,so quitting " << endl;
    glutDestroyWindow(win);
    exit(0);
  }
}
